import axios from 'axios';
import { useAuthStore } from '@/stores/auth';

// 创建API实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器 - 添加认证Token
api.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore();
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 用户相关API
export const userApi = {
  // 获取用户资料
  getProfile: () => api.get('/users/profile'),
  
  // 获取用户公开资料
  getUserById: (userId: string) => api.get(`/users/${userId}`),
  
  // 更新用户资料
  updateProfile: (data: any) => api.put('/users/profile', data),
  
  // 上传头像
  uploadAvatar: (formData: FormData) => api.post('/users/avatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }),
  
  // 搜索用户
  searchUsers: (keyword: string) => api.get(`/users/search?keyword=${keyword}`),
  
  // 发送好友请求
  sendFriendRequest: (userId: string) => api.post('/users/friend-request', { userId }),
  
  // 响应好友请求
  respondToFriendRequest: (requestId: string, action: 'accepted' | 'rejected') => 
    api.put('/users/friend-request', { requestId, action }),
  
  // 获取好友列表
  getFriends: () => api.get('/users/friends'),
  
  // 获取好友请求
  getFriendRequests: () => api.get('/users/friend-requests')
};

// 消息相关API
export const messageApi = {
  // 发送消息
  sendMessage: (receiverId: string, content: string, type = 'text') => 
    api.post('/messages', { receiver: receiverId, content, type }),
  
  // 获取与某用户的聊天记录
  getMessages: (userId: string) => api.get(`/messages/${userId}`),
  
  // 获取最近聊天列表
  getRecentChats: () => api.get('/messages/chats/recent')
};

export default api; 